const { sequelize } = require('../src/config/database');
const logger = require('../src/utils/logger');

async function syncDatabase(mode = 'alter', force = false) {
  try {
    console.log('🔄 开始数据库同步...');
    console.log(`📋 同步模式: ${mode}`);
    
    if (force) {
      console.log('⚠️ 警告: 将删除所有表并重新创建，数据将丢失！');
      const readline = require('readline');
      const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
      });
      
      const answer = await new Promise((resolve) => {
        rl.question('确认继续吗？(输入 "yes" 确认): ', resolve);
      });
      rl.close();
      
      if (answer.toLowerCase() !== 'yes') {
        console.log('❌ 操作已取消');
        process.exit(0);
      }
    }
    
    const syncOptions = {
      logging: console.log,
      force: mode === 'force' || force
    };
    
    if (mode === 'alter') {
      syncOptions.alter = true;
    }
    
    await sequelize.sync(syncOptions);
    
    console.log('✅ 数据库同步完成');
    
    // 显示表信息
    const tables = await sequelize.showAllSchemas();
    console.log('\n📊 数据库表信息:');
    console.table(tables);
    
  } catch (error) {
    console.error('❌ 数据库同步失败:', error.message);
    logger.error('数据库同步失败:', error);
    process.exit(1);
  } finally {
    await sequelize.close();
  }
}

async function showTables() {
  try {
    console.log('📊 当前数据库表信息:');
    
    const tables = await sequelize.showAllSchemas();
    console.table(tables);
    
    // 显示每个表的详细信息
    for (const table of tables) {
      try {
        const describeResult = await sequelize.getQueryInterface().describeTable(table.name);
        console.log(`\n📋 表 ${table.name} 结构:`);
        console.table(describeResult);
      } catch (error) {
        console.log(`❌ 无法获取表 ${table.name} 的结构信息`);
      }
    }
    
  } catch (error) {
    console.error('❌ 获取表信息失败:', error.message);
  } finally {
    await sequelize.close();
  }
}

async function resetDatabase() {
  try {
    console.log('🗑️ 开始重置数据库...');
    console.log('⚠️ 警告: 这将删除所有表和数据！');
    
    const readline = require('readline');
    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    
    const answer = await new Promise((resolve) => {
      rl.question('确认重置数据库吗？(输入 "RESET" 确认): ', resolve);
    });
    rl.close();
    
    if (answer !== 'RESET') {
      console.log('❌ 操作已取消');
      process.exit(0);
    }
    
    await sequelize.sync({ force: true, logging: console.log });
    console.log('✅ 数据库重置完成');
    
  } catch (error) {
    console.error('❌ 数据库重置失败:', error.message);
    process.exit(1);
  } finally {
    await sequelize.close();
  }
}

// 处理命令行参数
const args = process.argv.slice(2);
const command = args[0];
const mode = args[1];

switch (command) {
  case 'sync':
    syncDatabase(mode || 'alter');
    break;
  case 'force':
    syncDatabase('force', true);
    break;
  case 'alter':
    syncDatabase('alter');
    break;
  case 'tables':
    showTables();
    break;
  case 'reset':
    resetDatabase();
    break;
  case 'help':
  default:
    console.log('📖 数据库同步脚本使用方法:');
    console.log('');
    console.log('  node scripts/db-sync.js sync [mode]     # 同步数据库 (mode: alter/force)');
    console.log('  node scripts/db-sync.js alter           # 修改表结构 (保留数据)');
    console.log('  node scripts/db-sync.js force           # 强制重建表 (删除数据)');
    console.log('  node scripts/db-sync.js tables          # 显示表信息');
    console.log('  node scripts/db-sync.js reset           # 重置数据库');
    console.log('  node scripts/db-sync.js help            # 显示帮助');
    console.log('');
    console.log('📋 同步模式说明:');
    console.log('  alter: 修改表结构，保留现有数据');
    console.log('  force: 删除表并重新创建，数据会丢失');
    console.log('');
    console.log('💡 示例:');
    console.log('  node scripts/db-sync.js sync alter      # 安全同步');
    console.log('  node scripts/db-sync.js sync force       # 强制同步');
    break;
} 